package cn.lg.soar.system.biz.modules.auth.service.impl;

import cn.lg.soar.common.data.tree.ITreeResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.CurrentProxy;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.common.util.data.TreeUtil;
import cn.lg.soar.database.base.service.impl.TreeServiceImpl;
import cn.lg.soar.system.biz.config.SystemCacheKey;
import cn.lg.soar.system.biz.modules.auth.entity.Org;
import cn.lg.soar.system.biz.modules.auth.entity.OrgRole;
import cn.lg.soar.system.biz.modules.auth.entity.UserOrg;
import cn.lg.soar.system.biz.modules.auth.mapper.OrgMapper;
import cn.lg.soar.system.biz.modules.auth.model.OrgDto;
import cn.lg.soar.system.biz.modules.auth.model.OrgTree;
import cn.lg.soar.system.biz.modules.auth.service.IOrgService;
import cn.lg.soar.system.biz.modules.auth.service.OrgRoleService;
import cn.lg.soar.system.biz.modules.auth.service.UserOrgService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2021/8/21
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class OrgServiceImpl extends TreeServiceImpl<Long, OrgMapper, Org> implements IOrgService, CurrentProxy<IOrgService> {

    @Autowired
    private UserOrgService userOrgService;
    @Autowired
    private OrgRoleService orgRoleService;

    @Cacheable(value = SystemCacheKey.ORG_BY_ID, key = "#id")
    @Override
    public Org getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    public List<Org> getAncestorById(Long id) {
        if (DataUtil.isEmpty(id)) {
            return Collections.emptyList();
        }
        List<OrgTree> tree = proxy().tree();
        return ITreeResult.findLink(tree, x -> Objects.equals(x.getId(), id))
                .stream()
                .map(t -> {
                    Org org = new Org();
                    org.setId(t.getId());
                    org.setName(t.getName());
                    org.setType(t.getType());
                    org.setAlias(t.getAlias());
                    org.setDirector(t.getDirector());
                    return org;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<List<Org>> getAncestorListByIds(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<OrgTree> tree = proxy().tree();
        return ids.stream()
                .map(id -> ITreeResult.findLink(tree, x -> Objects.equals(x.getId(), id))
                        .stream()
                        .map(t -> {
                            Org org = new Org();
                            org.setId(t.getId());
                            org.setName(t.getName());
                            org.setType(t.getType());
                            org.setAlias(t.getAlias());
                            org.setDirector(t.getDirector());
                            return org;
                        })
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());
    }

    @Caching(evict = {
            @CacheEvict(value = { SystemCacheKey.ORG_ID_BY_USER_ALL }, allEntries = true),
            @CacheEvict(value = { SystemCacheKey.TREE }, key = "'org'")
    })
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Long create(OrgDto data) {
        Org convert = data.toOrg();
        AssertUtil.isTrue(this.save(convert), "创建组织机构失败");
        if (!CollectionUtils.isEmpty(data.getRoleIds())) {
            orgRoleService.setOrgRole(convert.getId(), data.getRoleIds());
        }
        return convert.getId();
    }

    @Caching(evict = {
            @CacheEvict(value = { SystemCacheKey.ORG_BY_ID }, key = "#entity.id"),
            @CacheEvict(value = { SystemCacheKey.ORG_ID_BY_USER_ALL }, allEntries = true),
            @CacheEvict(value = { SystemCacheKey.TREE }, key = "'org'")
    })
    @Override
    public boolean updateById(Org entity) {
        return super.updateById(entity);
    }

    @Caching(evict = {
            @CacheEvict(value = { SystemCacheKey.ORG_BY_ID }, key = "#id"),
            @CacheEvict(value = { SystemCacheKey.ORG_ID_BY_USER_ALL }, allEntries = true),
            @CacheEvict(value = { SystemCacheKey.TREE }, key = "'org'")
    })
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean removeById(Serializable id) {
        userOrgService.remove(Wrappers.<UserOrg>lambdaQuery().eq(UserOrg::getOrgId, id));
        orgRoleService.remove(Wrappers.<OrgRole>lambdaQuery().eq(OrgRole::getOrgId, id));
        return super.removeById(id);
    }

    @Override
    public List<Org> listByUserId(Long userId) {
        List<Long> orgIds = userOrgService.getOrgIds(userId);
        return listByIds(orgIds, SystemCacheKey.ORG_BY_ID);
    }

    @Override
    public List<Long> getInferiorsIds(Collection<Long> orgIds) {
        if (DataUtil.isEmpty(orgIds)) {
            return Collections.emptyList();
        }
        // 查所有数据
        List<Org> list = list(
                Wrappers.<Org>lambdaQuery().select(Org::getId, Org::getParentId)
        );
        // 组装树结构
        List<OrgTree> tree = ITreeResult.valueOf(list, 0L, OrgTree::new);
        List<OrgTree> res = new ArrayList<>();
        // 筛选获取子类数据
        TreeUtil.forEach(tree, (x) -> {
            if (orgIds.contains(x.getId()) && x.getChildren() != null) {
                res.addAll(x.getChildren());
            }
        });
        // 提取id
        List<Long> ids = new ArrayList<>(orgIds.size() << 4);
        TreeUtil.forEach(res, (x) -> {
                ids.add(x.getId());
        });
        return ids;
    }

    @Override
    public Map<Long, List<String>> nameLinkByIds(Collection<Long> ids) {
        List<OrgTree> tree = proxy().tree();
        Map<Long, List<String>> map = new HashMap<>(ids.size());
        for (Long id : ids) {
            List<String> names = TreeUtil.findLink(tree, (x) -> x.getId().equals(id))
                    .stream()
                    .map(OrgTree::getName)
                    .collect(Collectors.toList());
            map.put(id, names);
        }
        return map;
    }

    @Cacheable(value = SystemCacheKey.TREE, key = "'org'")
    @Override
    public List<OrgTree> tree() {
        List<Org> list = list(
                Wrappers.<Org>lambdaQuery()
                        .select(
                                Org::getId,
                                Org::getParentId,
                                Org::getType,
                                Org::getName,
                                Org::getAlias,
                                Org::getDirector
                        )
                        .eq(Org::getDisabled, false)
                        .orderByAsc(Org::getSort)
        );
        return ITreeResult.valueOf(list, 0L, OrgTree::new);
    }

    @Caching(evict = {
            @CacheEvict(value = { SystemCacheKey.ORG_BY_ID, SystemCacheKey.ORG_ID_BY_USER }, allEntries = true),
            @CacheEvict(value = { SystemCacheKey.TREE }, key = "'org'")
    })
    @Override
    public void clearCache() {}

    @Caching(evict = {
            @CacheEvict(value = { SystemCacheKey.ORG_BY_ID }, allEntries = true),
            @CacheEvict(value = { SystemCacheKey.TREE }, key = "'org'")
    })
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        userOrgService.remove(Wrappers.<UserOrg>lambdaQuery().in(UserOrg::getOrgId, list));
        orgRoleService.remove(Wrappers.<OrgRole>lambdaQuery().in(OrgRole::getOrgId, list));
        return super.removeByIds(list);
    }
}
